<template>
  <div class="purchaseForm">
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px">
      <el-form :inline="true">
        <el-form-item>
          <el-button type="primary" @click="showDialog" v-show="!dataDetail.id">新增</el-button>
        </el-form-item>
        <el-form-item v-if="!dataDetail.type || dataDetail.type == 0 || dataDetail.type == 1">
        <el-button type="info" @click="editForm" :disabled="!isRead">修改</el-button>
        </el-form-item>
        <el-form-item v-if="dataDetail.type == 2">
          <el-button type="warning" @click="withDraw">撤回</el-button>
        </el-form-item>
        <el-form-item v-if="dataDetail.type == 2 || dataDetail.type == 1">
          <el-button type="warning" @click="closeForm()">关闭</el-button>
        </el-form-item>
        <el-form-item v-if="dataDetail.type">
          <el-button type="primary" @click="deleteForm()">删除</el-button>
        </el-form-item>
        <el-form-item
          v-if="
            !dataDetail.type || dataDetail.type == 0 || dataDetail.type == 1
          "
        >
          <el-button type="primary" @click="saveFile(1)">保存</el-button>
        </el-form-item>
        <el-form-item v-if="dataDetail.type == 1">
          <el-button type="primary" @click="submitForm">提交</el-button>
        </el-form-item>
        <el-form-item v-if="dataDetail.type == 2">
          <el-button type="success" @click="approval">审核</el-button>
        </el-form-item>
        <el-form-item>
          <!-- 导出 -->
          <exportBtn
            :url="'wlcSysAll/checkOut'"
            :sendData="dataDetail"
            :state="1"
          ></exportBtn>
        </el-form-item>
        <el-form-item v-if="!dataDetail.type || dataDetail.type == 0">
          <el-button type="primary" @click="saveDraft">存为草稿</el-button>
        </el-form-item>
        <el-form-item v-if="!dataDetail.type || dataDetail.type == 0">
          <el-button type="success" @click="chooseDraft">选择草稿</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="success"
            @click="lookProcess"
            v-if="dataDetail.type && dataDetail.type != 0"
            >查审</el-button
          >
        </el-form-item>
      </el-form>
    </el-col>
    <el-col :span="24" class="toolbar">
      <div class="apply-data">
        <div class="ad-item">
          <div class="tit">单据编号:</div>
          <div class="text">{{ typeData.orderNum }}</div>
        </div>

        <div class="ad-item">
          <div class="tit">*申请日期:</div>
          <div class="text" style="width: 150px">
            <el-date-picker
              :disabled="isRead"
              v-model="typeData.uploadDay"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
            ></el-date-picker>
          </div>
        </div>
        <div class="ad-item">
          <div class="tit">*公司部门:</div>
          <!-- <div class="text">{{dataDetail.deptname}}</div> -->
          <div class="text" style="width: 130px" v-if="showCascader">
            <companyDepart
              @getCompanyDepart="getCompanyDepart"
              :companyDepartData="companyDepartData"
              :disabled="isRead"
            ></companyDepart>
          </div>
        </div>
        <div class="ad-item" v-loading="loadingUser">
          <div class="tit">*请购人:</div>
          <div class="text" style="width: 120px">
            <el-select
              :disabled="isRead"
              filterable
              v-model="typeData.userString"
              placeholder="请选择"
            >
              <el-option
                v-for="item in userArr"
                :key="item.cuserid"
                :label="item.userName"
                :value="item.cuserid + ',' + item.userName"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="ad-item">
          <div class="tit">*需求日期:</div>
          <div class="text" style="width: 150px">
            <el-date-picker
              :disabled="isRead"
              v-model="typeData.needDay"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
            ></el-date-picker>
          </div>
        </div>
        <div class="ad-item">
          <div class="tit">*采购类型:</div>
          <div class="text" style="width: 120px">
            <el-select
              :disabled="isRead"
              v-model="typeData.type"
              placeholder="请选择"
            >
              <el-option label="紧急采购" value="0"></el-option>
              <el-option label="零星采购" value="1"></el-option>
              <el-option label="合同采购" value="2"></el-option>
            </el-select>
          </div>
        </div>
        <div class="ad-item">
          <div class="tit">*建议供应商:</div>
          <div class="text" style="width: 120px">
            <el-select
              :disabled="isRead"
              v-model="typeData.supplier"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in supplierArr"
                :key="item.id"
                :label="item.supplierName"
                :value="item.supplierName + ',' + item.id"
              ></el-option>
            </el-select>
          </div>
        </div>
      </div>
    </el-col>
    <el-col :span="24" class="toolbar">
      <el-table :data="tableData" style="width: 100%" border row-key="id">
        <el-table-column
          label="序号"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="productName"
          label="产品名称"
          align="center"
        ></el-table-column>
        <el-table-column prop="file" label="附件" width="140" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.productUrl" style="margin-bottom: 5px">
              <el-button
                @click="showImg(scope.row.productUrl)"
                size="small"
                type="primary"
                >查看</el-button
              >
            </div>
            <div @click="getIndex(scope)">
              <el-upload
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                :auto-upload="false"
                :on-change="uploadFile"
                :on-remove="removeFile"
                :show-file-list="false"
                :disabled="isRead"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过50kb
                </div>
              </el-upload>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="invspec"
          label="规格型号"
          align="center"
        ></el-table-column>
        <!-- 未知字段 -->
        <el-table-column label="供应商" prop="supplierName"></el-table-column>
        <el-table-column label="质量标准" width="120" align="center">
          <template slot-scope="scope">
            <el-input
              :readonly="isRead"
              v-model="scope.row.qualityStandard"
              placeholder="质量标准"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="时间" width="120" align="center">
          <template slot-scope="scope">
            <el-button type="primary" @click="chooseTime(scope)"
              >选择时间</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="历史" align="center">
          <el-table-column
            prop="historical"
            label="采购量"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="histMaxMoney"
            label="最高价"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="histMinMoney"
            label="最低价"
            align="center"
          ></el-table-column>
          <el-table-column prop="histAvgMoney" label="平均价" align="center">
            <template slot-scope="scope">
              <p>
                {{
                  scope.row.histAvgMoney
                    ? (scope.row.histAvgMoney * 1).toFixed(2)
                    : 0
                }}
              </p>
            </template>
          </el-table-column>
          <el-table-column
            prop="contractPrice"
            label="合同价"
            align="center"
          ></el-table-column>
          <el-table-column label="是否含运费" align="center" width="100">
            <template slot-scope="scope">
              <p>是</p>
            </template>
          </el-table-column>
          <el-table-column label="付款方式">
            <template slot-scope="scope">
              <p>转账</p>
            </template>
          </el-table-column>
          <el-table-column
            width="100"
            prop="lastBuyer"
            label="上期采购员"
            align="center"
          ></el-table-column>
          <el-table-column label="历史评价" align="center"></el-table-column>
        </el-table-column>
        <el-table-column label="请购数据"  align="center">
          <el-table-column label="*单价(元)" align="center" width="210">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.requisitionsUnitPrice"
                :min="0"
                :disabled="isRead"
                :max="999999999999999999"
                placeholder="询价"
                @change="changePic(scope)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            prop="measurement"
            label="单位"
            align="center"
          ></el-table-column>
          <el-table-column label="*本期申请数量" align="center" width="210">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.requisitionsHowMany"
                :min="0"
                :disabled="isRead"
                :max="999999999999999999"
                placeholder="申请数量"
                @change="changePic(scope)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="*税率(询价)" align="center" width="210">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.requisitionsTaxRate"
                :min="0"
                :disabled="isRead"
                :max="1"
                placeholder="税率"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="*总价" align="center" width="210">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.inquiryAllMoneys"
                :min="0"
                :disabled="isRead"
                :max="999999999999999999"
                placeholder="总价"
              ></el-input-number>
            </template>
          </el-table-column>

          <el-table-column label="*是否含运费(询价)" align="center" width="140">
            <template slot-scope="scope">
              <el-select
                :disabled="isRead"
                v-model="scope.row.requisitionsIsFreight"
                placeholder="请选择"
              >
                <el-option label="是" value="Y"></el-option>
                <el-option label="否" value="N"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="*付款方式(询价)" align="center" width="140">
            <template slot-scope="scope">
              <el-input
                :maxlength="15"
                :readonly="isRead"
                v-model="scope.row.requisitionsPayType"
                placeholder="付款方式"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="*地址及联系方式(询价)"
            align="center"
            width="200"
          >
            <template slot-scope="scope">
              <el-input
                resize="none"
                :readonly="isRead"
                v-model="scope.row.requisitionsAddressPhone"
                placeholder="地址及联系方式"
                type="textarea"
                autosize
                :maxlength="255"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="*现有库存" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                :maxlength="10"
                :readonly="isRead"
                v-model="scope.row.requisitionsNowHave"
                placeholder="库存"
              ></el-input>
              <!-- <el-input-number
            v-model="scope.row.requisitionsNowHave"
            :min="0"
            :disabled="isRead"
            :max="999999999"
            placeholder="库存"
            ></el-input-number>-->
            </template>
          </el-table-column>
          <el-table-column label="*用途" align="center" width="160">
            <template slot-scope="scope">
              <el-input
                :maxlength="20"
                :readonly="isRead"
                v-model="scope.row.requisitionsHowUse"
                placeholder="用途"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" width="220">
            <template slot-scope="scope">
              <el-input
                :readonly="isRead"
                v-model="scope.row.requisitionsRemark"
                placeholder="提示：文字：XXXX ; 购买链接：http://XX.XX"
                type="textarea"
                :autosize="{maxRows: 2}"
                resize="none"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column label="最终审批数据" align="center" :label-class-name="'labelFont'" >
          <el-table-column label="单价" align="center">
            <template slot-scope="scope">
              <div>
                {{
                  scope.row.wlcSysInquiryLast
                    ? scope.row.wlcSysInquiryLast.inquiryUnitPrice
                    : ""
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="总价" align="center">
            <template slot-scope="scope">
              <div>
                {{
                  scope.row.wlcSysInquiryLast
                    ? scope.row.wlcSysInquiryLast.inquiryAllMoneys
                    : ""
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="税率" align="center">
            <template slot-scope="scope">
              <div>
                {{
                  scope.row.wlcSysInquiryLast
                    ? scope.row.wlcSysInquiryLast.inquiryTaxRate
                    : ""
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="付款方式" align="center">
            <template slot-scope="scope">
              <div>
                {{
                  scope.row.wlcSysInquiryLast
                    ? scope.row.wlcSysInquiryLast.inquiryPayType
                    : ""
                }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="是否含运费" align="center" width="100">
            <template slot-scope="scope">
              <div>
                {{
                  scope.row.wlcSysInquiryLast
                    ? scope.row.wlcSysInquiryLast.inquiryIsFreight == "Y"
                      ? "是"
                      : "否"
                    : ""
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="供应商名称" align="center" width="100">
            <template slot-scope="scope">
              <div>
                {{
                  scope.row.wlcSysInquiryLast
                    ? scope.row.wlcSysInquiryLast.inquiryCustname
                    : ""
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="地址及联系方式" align="center" width="120">
            <template slot-scope="scope">
              <div>
                {{
                  scope.row.wlcSysInquiryLast
                    ? scope.row.wlcSysInquiryLast.inquiryAddressPhone
                    : ""
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template slot-scope="scope">
              <div>
                {{
                  scope.row.wlcSysInquiryLast
                    ? scope.row.wlcSysInquiryLast.inquiryRemark
                    : ""
                }}
              </div>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </el-col>

    <!-- 选择商品弹窗 -->
    <el-dialog
      title="商品列表"
      :visible.sync="dialogTableVisible"
      width="80%"
      top="7vh"
    >
      <div class="diaSearch">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="商品名称:">
            <el-input
              v-model="formInline.name"
              placeholder="商品名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="productList"
        height="50vh"
        @selection-change="handleSelectionChange"
        ref="multipleTable"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          fixed
        ></el-table-column>
        <el-table-column
          property="productName"
          label="产品名称"
          align="center"
        ></el-table-column>
        <!-- <el-table-column property="name" label="附件" align="center"></el-table-column> -->
        <el-table-column label="规格型号" align="center">
          <template slot-scope="scope">
            <p>{{ scope.row.invspec }}</p>
          </template>
        </el-table-column>
        <el-table-column
          property="invpinpai"
          label="品牌"
          align="center"
        ></el-table-column>
        <el-table-column
          property="measurement"
          label="单位"
          align="center"
        ></el-table-column>
      </el-table>
      <div class="page-size">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="page.pageSize"
          :current-page="page.page"
          @current-change="changeSize"
        ></el-pagination>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureProduct()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 时间弹窗 -->
    <el-dialog title="选择时间" :visible.sync="dialogTime" width="50%">
      <el-form :model="time_obj">
        <el-form-item label>
          <el-row :gutter="20">
            <el-col :span="11">
              <el-date-picker
                type="date"
                placeholder="开始日期"
                v-model="time_obj.startTime"
                style="width: 100%"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-col>
            <el-col class="line" :span="2" align="center">----</el-col>
            <el-col :span="11">
              <el-date-picker
                type="date"
                placeholder="结束日期"
                v-model="time_obj.endTime"
                style="width: 100%"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTime = false">取 消</el-button>
        <el-button type="primary" @click="sureTime()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 选择草稿 -->
    <el-dialog
      title="草稿列表"
      :visible.sync="dialogDraft"
      width="80%"
      top="7vh"
    >
      <div class="diaSearch">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <!-- <el-form-item label="草稿名称:">
            <el-input v-model="formInline.productName" placeholder="草稿名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>-->
        </el-form>
      </div>
      <el-table :data="draftList" height="50vh" ref="multipleTable">
        <!-- <el-table-column property="productName" label="产品名称" align="center"></el-table-column> -->
        <!-- <el-table-column property="name" label="附件" align="center"></el-table-column> -->
        <!-- <el-table-column label="规格型号" align="center">
          <template slot-scope="scope">
            <p>{{ scope.row.invspec}}</p>
          </template>
        </el-table-column>
        <el-table-column property="supplierName" label="供应商" align="center"></el-table-column>
        <el-table-column property="taxRate" label="税率" align="center"></el-table-column>
        <el-table-column property="unitweight" label="质量标准" align="center"></el-table-column>
        <el-table-column property="measurement" label="单位" align="center"></el-table-column>-->
        <el-table-column
          property="psnname"
          label="请购人"
          align="center"
        ></el-table-column>
        <el-table-column
          property="createtime"
          label="创建日期"
          align="center"
        ></el-table-column>
        <el-table-column
          property="orderNum"
          label="请购单号"
          align="center"
        ></el-table-column>
        <el-table-column align="center">
          <template slot-scope="scope">
            <el-button size="small" @click="draftSure(scope.row)"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 查审弹窗 -->
    <el-dialog
      title="查审"
      :visible.sync="dialogInvestigate"
      width="40%"
      top="7vh"
    >
      <approvalProcess
        v-if="dialogInvestigate"
        :detail="dataDetail"
        @hideInves="hideInves"
      ></approvalProcess>
    </el-dialog>
    <!-- 展示图片 -->
    <el-dialog title="附件" :visible.sync="dialogImgShow">
      <div class="showImgDiv">
        <img :src="showImgUrl" alt />
      </div>
    </el-dialog>
    <el-col :span="24" class="toolbar">
      <div class="sign-remarks">
        <!-- <div class="tit">备注:</div> -->
        <el-form ref="form" label-width="80px">
          <el-form-item label="备注">
            <el-input v-model="typeData.remark" :disabled="isRead"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-col>
    <el-col :span="24" class="toolbar">
      <div class="sign-data">
        <div class="sd-item">制单人 : {{ dataDetail.singlePerson }}</div>
        <div class="sd-item">审核人 : {{ dataDetail.auditor }}</div>
        <div class="sd-item">审核时间 : {{ dataDetail.auditTime }}</div>
        <div class="sd-item">变更人 : {{ dataDetail.modifiername }}</div>
        <div class="sd-item">变更日期 : {{ dataDetail.modifytime }}</div>
      </div>
    </el-col>
  </div>
</template>
<script>
import {
  poOrderList,
  getPrice,
  wlcSysAllAdd,
  wlcSysAllAuditSubmit,
  wlcSysAllListByDraft,
  wlcSysAllList,
  wlcSysAllRemove,
  wlcSysAllSubmit,
  wlcSysAllUpdate,
  wlcSysAllListByOrder,
  bdInvbasdocUploadImage,
  wlcSysAllGetContractNo,
  wlcSysAllWithdrawTicket,
  wlcSysAllCloseTicket,
} from "../../api/api";
import {
  omJobSelectBdCorp,
  omJobSelectBdDeptdoc,
  smUserList,
} from "../../api/baseSetting";
import { supplierList } from "../../api/baseSetting";
import approvalProcess from "../components/approvalProcess";
import exportBtn from "../components/exportBtn";
import moment from "moment";
import companyDepart from "../components/companyDepart";
export default {
  components: {
    approvalProcess,
    exportBtn,
    companyDepart,
  },
  data() {
    return {
      showCascader: true,
      //请购单数据
      tableData: [],
      //搜索商品的关键字
      formInline: {
        name: "",
      },
      companyDepartData: [], //传给公司部门的参数
      loadingUser: false, //请购人是否加载中
      isRead: false, //是否只读
      page: {
        page: 1,
        pageSize: 10,
      },
      total: 0,
      productList: [], //商品列表
      dialogTableVisible: false, //显示可购买商品列表
      buyProduct: [], //选中要购买的商品
      buyProductSave: [], //点击换页 选择要购买的商品保存住

      dialogTime: false, //选择时间弹窗
      dialogInvestigate: false, //查审弹窗
      time_obj: {
        startTime: "",
        endTime: "",
      },
      // 请购单中被选择时间的那一条数据
      selectData: {
        data: {},
        index: null,
      },
      //选择附件  请购单被选中的那一条数据
      uploadData: {
        data: {},
        index: null,
      },
      dialogDraft: false, //是否显示选择草稿的弹窗
      draftList: [], //草稿列表
      //草稿的分页数据
      drafPage: {
        total: 0,
        pageSize: 10,
        page: 1,
      },
      //供应商和采购类型
      typeData: {
        orderNum: "",
        type: "",
        supplier: "",
        needDay: "",
        uploadDay: "", //申请日期
        userString: "", //请购人参数字符串
        pkCorp: "", //公司id和名称
        pkDeptdoc: "", //部门id和名称

        groupId: "",
        groupName: "",
        corpTypeId: "",
        corpTypeName: "",
        unitnameId: "",
        unitname: "",
        deptnameId: "",
        deptname: "",
      },
      //供应商列表
      supplierArr: [],
      dataDetail: {}, //从后端拿到的请购单详情
      companyList: [], //公司列表
      departList: [], //部门列表
      userArr: [], //请购人列表
      showImgUrl: "", //展示图片路径
      dialogImgShow: false, //是否展示图片
    };
  },
  created() {
    if (this.$route.query.id) {
      this.showCascader = false;
      this.getDetail(
        this.$route.query.id,
        this.$route.query.buyType,
        this.$route.query.again
      );
    }
  },
  mounted() {
    this.getList();
    this.getSupple();
    // this.getCompany();
    // this.getDepart();
    this.getUser();

    this.getDraft(); //获取草稿列表
  },
  methods: {
    //改变总价
    changePic(e) {
      let index = e.$index;
      this.tableData[index].inquiryAllMoneys =
        (e.row.requisitionsUnitPrice || 0) * (e.row.requisitionsHowMany || 0);
    },
    //选择公司部门
    getCompanyDepart(e) {
      this.typeData.groupId = e[0].value;
      this.typeData.groupName = e[0].label;

      this.typeData.corpTypeId = e[1].value;
      this.typeData.corpTypeName = e[1].label;

      this.typeData.unitnameId = e[2].value;
      this.typeData.unitname = e[2].label;

      this.typeData.deptnameId = e[3].pkDeptdoc;
      this.typeData.deptname = e[3].deptname;
    },
    //关闭查审
    hideInves() {
      this.dialogInvestigate = false;
      if (this.$route.query.id) {
        this.getDetail(
          this.$route.query.id,
          this.$route.query.buyType,
          this.$route.query.again
        );
      }
    },
    //关闭
    closeForm() {
      this.$confirm("确认关闭?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((res) => {
          wlcSysAllCloseTicket([
            {
              id: this.dataDetail.id,
            },
          ]).then((res) => {
            this.$message({
              type: "success",
              message: "关闭成功!",
            });
            this.getDetail(this.dataDetail.id, this.dataDetail.buyType);
          });
        })
        .catch(() => {});
    },
    //删除
    deleteForm() {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          wlcSysAllRemove([{ id: this.dataDetail.id }]).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.$router.go(-1);
          });
        })
        .catch(() => {});
    },
    //点击撤回按钮
    withDraw() {
      this.$confirm("确认撤回该请购单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          wlcSysAllWithdrawTicket([
            {
              id: this.dataDetail.id,
              buyType: this.dataDetail.buyType,
              deptnameId: this.dataDetail.deptnameId,
            },
          ]).then((res) => {
            this.$message({
              type: "success",
              message: "撤回成功!",
            });
            this.$router.go(-1);
          });
        })
        .catch(() => {});
    },
    //展示图片
    showImg(url) {
      this.showImgUrl = url;
      this.dialogImgShow = true;
    },
    //筛选用户
    remoteMethod(userName) {
      this.getUser(userName);
    },
    //获取用户列表
    getUser(userName) {
      this.loadingUser = true;
      smUserList({
        // userName,
        page: {
          page: 1,
          pageSize: 100000,
        },
      }).then((res) => {
        this.loadingUser = false;
        this.userArr = res.records;
      });
    },
    //选择公司
    companyChange(e) {
      let id = e.split(",")[0];
      this.getDepart(id);
      this.typeData.pkDeptdoc = "";
    },
    //部门列表
    getDepart(id) {
      omJobSelectBdDeptdoc({ pkCorp: id }).then((res) => {
        this.departList = res;
      });
    },
    //公司列表
    getCompany() {
      omJobSelectBdCorp({}).then((res) => {
        this.companyList = res;
      });
    },
    //点击查审
    lookProcess() {
      this.dialogInvestigate = true;
    },
    //保存为草稿
    saveDraft() {
      if (!this.typeData.type) {
        this.$message({
          message: "请选择采购类型",
          type: "warning",
        });
        return;
      }
      this.$confirm("确认存为草稿?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var list = this.tableData;
          for (var i = 0; i < list.length; i++) {
            list[i].isFreight = "Y";
            list[i].payType = "转账";
          }
          var sendData = {
            wlcSysBacks: list,
            orderNum: this.typeData.orderNum,
            needDay: this.typeData.needDay,
            buyType: this.typeData.type,
            custname: this.typeData.supplier.split(",")[0],
            custId: this.typeData.supplier.split(",")[1],
            groupId: this.typeData.groupId,
            groupName: this.typeData.groupName,

            corpTypeId: this.typeData.corpTypeId,
            corpTypeName: this.typeData.corpTypeName,
            //公司
            unitnameId: this.typeData.unitnameId,
            unitname: this.typeData.unitname,
            //部门
            deptnameId: this.typeData.deptnameId,
            deptname: this.typeData.deptname,
            psnnameId: this.typeData.userString.split(",")[0],
            psnname: this.typeData.userString.split(",")[1],
            uploadDay: this.typeData.uploadDay,
            remark: this.typeData.remark,
            type: 0,
          };
          if (this.dataDetail.id) {
            sendData.id = this.dataDetail.id;
            wlcSysAllUpdate(sendData).then((res) => {
              this.$message({
                message: "保存成功",
                type: "success",
              });
              this.getDraft();
            });
          } else {
            wlcSysAllAdd(sendData).then((res) => {
              this.$message({
                message: "保存成功",
                type: "success",
              });
              this.getDraft();
            });
          }
        })
        .catch(() => {});
    },
    //获取草稿列表
    getDraft() {
      wlcSysAllListByDraft({ type: 0 }).then((res) => {
        this.draftList = res;
      });
    },
    //点击选择草稿
    chooseDraft() {
      this.dialogDraft = true;
    },
    //草稿点击选择
    draftSure(data) {
      this.dialogDraft = false;
      this.getDetail(data.id, data.buyType);
    },
    //草稿翻页
    changeDrafSize() {
      this.drafPage.page = 1;
      this.getDraft();
    },
    //点击修改
    editForm() {
      if (this.dataDetail.type == 2) {
        this.$message({
          message: "提交后的数据,不可修改",
          type: "warning",
        });
        return;
      }
      this.isRead = false;
    },
    //点击提交
    submitForm() {
      if (!this.typeData.type) {
        this.$message({
          message: "请选择采购类型",
          type: "warning",
        });
        return;
      }
      this.$confirm("确认提交?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.isRead = true;
          var data = this.dataDetail;
          var list = this.tableData;
          // for (var i = 0; i < list.length; i++) {
          //   list[i].isFreight = "Y";
          //   list[i].payType = "转账";
          // }
          orderNum: this.typeData.orderNum;
          data.wlcSysBacks = list;
          data.needDay = this.typeData.needDay;
          data.buyType = this.typeData.type;
          data.custname = this.typeData.supplier.split(",")[0];
          data.custId = this.typeData.supplier.split(",")[1];

          // data.unitnameId = this.typeData.pkCorp.split(",")[0];
          // data.unitname = this.typeData.pkCorp.split(",")[1];
          // data.deptnameId = this.typeData.pkDeptdoc.split(",")[0];
          // data.deptname = this.typeData.pkDeptdoc.split(",")[1];

          data.groupId = this.typeData.groupId;
          data.groupName = this.typeData.groupName;

          data.corpTypeId = this.typeData.corpTypeId;
          data.corpTypeName = this.typeData.corpTypeName;
          //公司
          data.unitnameId = this.typeData.unitnameId;
          data.unitname = this.typeData.unitname;
          //部门
          data.deptnameId = this.typeData.deptnameId;
          data.deptname = this.typeData.deptname;

          data.psnnameId = this.typeData.userString.split(",")[0];
          data.psnname = this.typeData.userString.split(",")[1];
          data.uploadDay = this.typeData.uploadDay;
          data.remark = this.typeData.remark;
          data.type = 2;
          wlcSysAllSubmit(data).then((res) => {
            this.getDetail(res.id, res.buyType);
            this.$message({
              type: "success",
              message: "提交成功!",
            });
          });
        })
        .catch(() => {});
    },
    //保存文件
    saveFile(type) {
      if (!this.typeData.type) {
        this.$message({
          message: "请选择采购类型",
          type: "warning",
        });
        return;
      }
      if (!this.typeData.uploadDay) {
        this.$message({
          message: "请选择申请日期",
          type: "warning",
        });
        return;
      }
      if (!this.typeData.deptnameId) {
        this.$message({
          message: "请选择公司部门",
          type: "warning",
        });
        return;
      }
      if (!this.typeData.userString) {
        this.$message({
          message: "请选择请购人",
          type: "warning",
        });
        return;
      }
      if (!this.typeData.needDay) {
        this.$message({
          message: "请选择需求日期",
          type: "warning",
        });
        return;
      }
      if (!this.typeData.supplier) {
        this.$message({
          message: "请选择建议供应商",
          type: "warning",
        });
        return;
      }
      if (!this.typeData.supplier) {
        this.$message({
          message: "请选择建议供应商",
          type: "warning",
        });
        return;
      }

      var list = this.tableData;
      for (let i = 0; i < this.tableData.length; i++) {
        if (
          !list[i].requisitionsUnitPrice &&
          list[i].requisitionsUnitPrice != 0
        ) {
          this.$message({
            message: "请输入单价",
            type: "warning",
          });
          return;
        }
        if (!list[i].requisitionsTaxRate && list[i].requisitionsTaxRate != 0) {
          this.$message({
            message: "请输入税率",
            type: "warning",
          });
          return;
        }
        if (!list[i].requisitionsIsFreight) {
          this.$message({
            message: "请选择是否含运费",
            type: "warning",
          });
          return;
        }
        if (!list[i].requisitionsPayType) {
          this.$message({
            message: "请输入付款方式",
            type: "warning",
          });
          return;
        }
        if (!list[i].requisitionsAddressPhone) {
          this.$message({
            message: "请输入地址及联系方式",
            type: "warning",
          });
          return;
        }
        if (!list[i].requisitionsNowHave) {
          this.$message({
            message: "请输入现有库存",
            type: "warning",
          });
          return;
        }
        if (!list[i].requisitionsHowUse) {
          this.$message({
            message: "请输入用途",
            type: "warning",
          });
          return;
        }
        if (!list[i].requisitionsHowMany) {
          this.$message({
            message: "请输入本期申请数量",
            type: "warning",
          });
          return;
        }
        if (!list[i].inquiryAllMoneys && list[i].inquiryAllMoneys != 0) {
          this.$message({
            message: "请输入总价",
            type: "warning",
          });
          return;
        };
        //重新提交
        if(this.$route.query.again){
          list[i].id = '';
          list[i].allId = '';
        }
      }
      this.$confirm("确认保存?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          for (var i = 0; i < list.length; i++) {
            list[i].isFreight = "Y";
            list[i].payType = "转账";
            list[i].histAvgMoney = (list[i].histAvgMoney * 1).toFixed(2);
            list[i].histMaxMoney = (list[i].histMaxMoney * 1).toFixed(2);
            list[i].histMinMoney = (list[i].histMinMoney * 1).toFixed(2);
          }
          console.log(this.dataDetail);
          wlcSysAllAdd({
            wlcSysBacks: list,
            // orderNum: this.$route.query.again ?'':this.typeData.orderNum,
            orderNum: this.typeData.orderNum,
            needDay: this.typeData.needDay,
            buyType: this.typeData.type,
            custname: this.typeData.supplier.split(",")[0],
            custId: this.typeData.supplier.split(",")[1],
            groupId: this.typeData.groupId,
            groupName: this.typeData.groupName,

            corpTypeId: this.typeData.corpTypeId,
            corpTypeName: this.typeData.corpTypeName,
            //公司
            unitnameId: this.typeData.unitnameId,
            unitname: this.typeData.unitname,
            //部门
            deptnameId: this.typeData.deptnameId,
            deptname: this.typeData.deptname,
            psnnameId: this.typeData.userString.split(",")[0],
            psnname: this.typeData.userString.split(",")[1],
            uploadDay: this.typeData.uploadDay,
            remark: this.typeData.remark,
            type: 1,
          }).then((res) => {
            this.getDetail(res.id, res.buyType);
            this.$message({
              message: "保存成功,确认无误请点击提交",
              type: "success",
            });
          });
        })
        .catch(() => {});
    },

    //商品列表点击查询
    onSubmit() {
      this.page.page = 1;
      this.getList();
    },
    //选中商品点击确定
    sureProduct() {
      if (this.dataDetail.id) {
        this.tableData = [...this.buyProductSave, ...this.buyProduct];
      } else {
        this.tableData = [
          ...this.tableData,
          ...this.buyProductSave,
          ...this.buyProduct,
        ];
      }

      this.buyProductSave = [];
      this.buyProduct = [];
      this.dataDetail = {};
      this.isRead = false;
      this.dialogTableVisible = false;
      wlcSysAllGetContractNo({}).then((res) => {
        this.typeData.orderNum = res;
        this.typeData.uploadDay = moment().format("YYYY-MM-DD");
      });
    },
    //点击新增
    showDialog() {
      this.dialogTableVisible = true;
    },
    //商品列表  点击选中
    handleSelectionChange(val) {
      console.log(val);
      this.buyProduct = val;
    },
    //翻页
    changeSize(page) {
      this.page.page = page;
      this.getList();
    },
    //获取可购产品的列表
    getList() {
      this.buyProductSave = [...this.buyProductSave, ...this.buyProduct];
      let page = {
        page: this.page,
      };
      let data = Object.assign({}, page, this.formInline); //给一个空对象作为target，这样改变的是空对象
      poOrderList(data).then((res) => {
        this.productList = res.records;
        this.total = res.total;
      });
    },
    //点击上传文件
    uploadFile(file, fileList) {
      console.log(file);

      let type = file.name.split(".").pop();
      if (type == "png" || type == "jpg") {
      } else {
        this.$message({
          message: "请上传png,jpg格式的图片",
          type: "warming",
        });
        return;
      }
      if (file.size > 50 * 1024) {
        this.$message({
          message: "图片不可大于50kb",
          type: "warming",
        });
        return;
      }
      var data = new FormData();
      data.append("file", file.raw);
      bdInvbasdocUploadImage(data).then((res) => {
        this.$message({
          message: "上传成功",
          type: "success",
        });
        this.tableData[this.uploadData.index].productUrl = res.filePath;
        this.$set(
          this.tableData[this.uploadData.index],
          "fileName",
          res.fileName
        );
      });
    },
    //获取选择文件的第几条数据上传附件
    getIndex(e) {
      this.uploadData.index = e.$index;
    },
    //删除文件
    removeFile(file, fileList) {
      console.log(file);
      console.log(fileList);
    },

    //显示选择时间弹窗
    chooseTime(obj) {
      if (this.isRead) {
        return;
      }
      this.selectData = {
        data: obj.row,
        index: obj.$index,
      };
      this.dialogTime = true;
    },
    //选择时间弹窗 点击确认
    sureTime() {
      if (this.time_obj.startTime && this.time_obj.endTime) {
        var data = {
          startTime: this.time_obj.startTime,
          endTime: this.time_obj.endTime,
          pkInvbasdoc: this.selectData.data.pkInvbasdoc,
        };

        getPrice(data).then((res) => {
          this.selectData.data.histAvgMoney = res.histAvgMoney || 0;
          this.selectData.data.histMaxMoney = res.histMaxMoney || 0;
          this.selectData.data.histMinMoney = res.histMinMoney || 0;
          this.selectData.data.historical = res.historical || 0;
          this.selectData.data.lastBuyerPeasonName = res.lastBuyerPeasonName;
          this.selectData.data.lastBuyerPeasonId = res.lastBuyerPeasonId;

          this.selectData.data.histTimeEnd = data.endTime;
          this.selectData.data.histTimeStart = data.startTime;
          // this.tableData[this.selectData.index] = this.selectData.data;
          this.$set(
            this.tableData[this.selectData.index],
            this.selectData.data
          );
        });
        this.dialogTime = false;
        // this.time_obj={
        //   startTime:'',
        //   endTime:'',
        // }
      } else {
        this.$message({
          message: "请选择时间",
          type: "warning",
        });
      }
    },
    //点击审核
    approval() {
      // var data = this.dataDetail;
      let data = Object.assign({}, this.dataDetail);
      let reason = "";
      this.$prompt("请输入理由(通过可不填写)", "是否审批通过", {
        confirmButtonText: "通过",
        cancelButtonText: "不通过",
        type: "warning",
        distinguishCancelAndClose: true,
        beforeClose: (action, instance, done) => {
          console.log(action, instance.inputValue);
          reason = instance.inputValue || "";
          if (action == "cancel") {
            if (instance.inputValue) {
              done();
            } else {
              this.$message({
                type: "warning",
                message: "请输入拒绝理由",
              });
            }
          } else {
            done();
          }
        },
      })
        .then((val) => {
          data.type = 2;
          data.reason = reason;
          wlcSysAllAuditSubmit([data])
            .then((res) => {
              this.$message({
                type: "success",
                message: "审批成功!",
              });
            })
            .catch((err) => {});
        })
        .catch((action) => {
          console.log(action);
          if (action == "cancel") {
            data.type = 4;
            data.reason = reason;
            console.log(data)
            wlcSysAllAuditSubmit([data]).then((res) => {
              this.$message({
                type: "warning",
                message: "审批不通过!",
              });
            });
          }
          // message: action === 'cancel'
        });
    },

    //获取供应商列表
    getSupple() {
      supplierList({
        page: {
          page: 1,
          pageSize: 10000,
        },
      }).then((res) => {
        this.supplierArr = res.records;
      });
    },
    //获取请购单详情
    getDetail(id, buyType, again) {
      wlcSysAllListByOrder({ id, buyType }).then((res) => {
        this.tableData = res.wlcSysBacks;
        this.dataDetail = res;
        if (again) {
          this.isRead = false;
          this.dataDetail.type = "";
        } else {
          this.isRead = true;
        }
        this.getDepart(res.unitnameId);
        this.typeData = {
          // type: res.buyType.toString(),
          type: this.dataDetail.buyType.toString(),
          supplier: res.custId ? res.custname + "," + res.custId : "",
          needDay: res.needDay,
          // pkCorp: res.unitnameId + "," + res.unitname, //公司id和名称
          // pkDeptdoc: res.deptnameId + "," + res.deptname, //部门id和名称
          groupId: res.groupId,
          groupName: res.groupName,
          corpTypeId: res.corpTypeId,
          corpTypeName: res.corpTypeName,
          unitnameId: res.unitnameId,
          unitname: res.unitname,
          deptnameId: res.deptnameId,
          deptname: res.deptname,

          userString: res.psnnameId + "," + res.psnname,
          uploadDay: res.uploadDay,
          remark: res.remark,
          orderNum: res.orderNum,
        };
        this.showCascader = true;
        this.companyDepartData = [
          res.groupId,
          res.corpTypeId,
          res.unitnameId,
          res.deptnameId,
        ];
      });
    },
  },
};
</script>

<style lang="less" scoped>
.purchTable {
  max-height: 500px;
}
.apply-data {
  display: flex;
  flex-wrap: wrap;
  .ad-item {
    display: flex;
    height: 30px;
    line-height: 30px;
    margin-right: 20px;
    align-items: center;
    width: 250px;
    color: #666;
    font-size: 14px;
  }
}
.sign-remarks {
  width: 100%;
  border-bottom: 1px solid #999;
  font-size: 14px;
  height: 40px;
  line-height: 40px;
  color: #333;
  padding-bottom: 5px;
}
.sign-data {
  display: flex;
  .sd-item {
    width: 18%;
    color: #333;
  }
}
.page-size {
  text-align: right;
  margin-top: 10px;
}
.showImgDiv {
  width: 100%;
  img {
    width: 100%;
  }
}
</style>
<style lang="less">
.purchaseForm {
  .el-date-editor.el-input {
    width: 100%;
  }
  .ad-item {
    .el-input__inner {
      height: 25px;
      line-height: 25px;
    }

    .el-input__suffix {
      line-height: 50px;
    }
    .el-input__prefix {
      .el-input__icon {
        line-height: 30px;
      }
    }
  }
  .el-table--scrollable-x .el-table__body-wrapper {
    overflow: auto;
    max-height: 350px;
  }
}
</style>
